package controllers;


import java.util.*;

import play.data.binding.As;
import play.data.validation.Required;
import play.mvc.*;

import models.*;
import models.User.Role;

public class Discount extends ConnectedUser {

	public static void list() {
		list(null);
	}
	
	public static void list(Long userId) {
		List<models.Discount> activeDiscounts;
		if(userId != null) {
			User partner = User.findById(userId);
			activeDiscounts = connectedUser.getActiveDiscountsWith(partner);
		} else {
			activeDiscounts = connectedUser.getActiveDiscounts();
		}

		render(activeDiscounts);
	}

	public static void offer() {
		List<User> discountReceivers = new ArrayList<User>();
		if(connectedUser.getUserRole() == Role.CLUB) {
			discountReceivers = RetailUser.findAll();
		}
		if(connectedUser.getUserRole() == Role.RETAILER) {
			discountReceivers = ClubUser.findAll();
		}
		
		render(discountReceivers);
	}
	
	/**
	 * Accept/reject new discounts
	 */
	public static void approve() {
		List<models.Discount> discountsWaiting = connectedUser.getDiscountsWaitingApproval();

		if(discountsWaiting.size() == 0){
			renderArgs.put("notice", "You don't have any incoming discounts");
		}
		
		render(discountsWaiting);
	}
	
	public static void accept(@Required Long id) {
		models.Discount discount = models.Discount.findById(id);
		discount.accept();
		
		flash.success("Accepted discount \"%s\" with \"%s\"", discount.description, discount.discountCreator.userName);
		
		if(connectedUser.getDiscountsWaitingApproval().size() > 0) {
			approve();
		} else {
			list();
		}
	}
	
	public static void reject(@Required Long id) {
		models.Discount discount = models.Discount.findById(id);
		discount.reject();
		
		flash.put("notice", "Rejected discount \"" + discount.description + "\" with \"" + discount.discountCreator.userName);
		
		if(connectedUser.getDiscountsWaitingApproval().size() > 0) {
			approve();
		} else {
			list();
		}
	}

	public static void submitDiscount(@Required String description,
			@Required @As("MM/dd/yy") Date expirationDate,
			@Required String discountReceiverId,
			String picUrl) {
		String userRole = identifyUser();
		if(validation.hasErrors()) {
			render("Discount/offer.html", userRole);
		}
	    connectedUser.createDiscount(description, expirationDate, picUrl, (User)(ClubUser.findById(Long.parseLong(discountReceiverId)))).save();
		flash.success("Discount saved.");
		render("Discount/offer.html", userRole);
	}
}
